<template>
  <!-- 图数据导入 -->
  <a-form :form="form" class="form-section">
    <a-form-item
      label="导入文件"
      :label-col="{ span: 3 }"
      :label-align="'left'"
    >
      <div class="form-item-container">
        <a-upload
          v-decorator="[
            'file',
            {
              rules: [
                {
                  validator: (rule, value, callback) => {
                    if (fileList.length === 0) {
                      callback('请上传文件!')
                      return false
                    }
                    return true
                  },
                },
              ],
            },
          ]"
          :custom-request="uploadDataset"
          accept=".csv,.json,.gml"
          :file-list="fileList"
          class="data-upload-button"
          :before-upload="beforeUpload"
          @change="handleUpload"
        >
          <a-button style="width: 200px;">
            <a-icon-font type="iconshujuguanli-daorushuju" />
            <span style="margin-left: 7px;">选择文件</span>
          </a-button>
        </a-upload>
        <!-- 已上传文件 -->
        <uploaded-file-name
          v-if="fileList.length !== 0"
          :file-name="fileList[0].name"
          :min-width="150"
          :max-width="200"
          @delete="deleteFile"
        />
      </div>
    </a-form-item>
    <!-- 选择分类 -->
    <a-form-item
      label="选择文件夹"
      :label-col="{ span: 8 }"
      :label-align="'left'"
      required
      :rules="[{ required: true, message: '请选择文件夹!' }]"
    >
      <a-select
        v-decorator="[
          'categoryId',
          {
            rules: [{ required: true, message: '请选择文件夹!' }],
            initialValue: selectedCategoryId,
          },
        ]"
        placeholder="请选择"
        class="select-box"
        size="small"
        style="width: 316px;"
        @change="selectedCategoryIdChanged"
      >
        <a-select-option
          v-for="category in categorySelectOptions"
          :key="category.categoryId"
          :value="category.categoryId"
          >{{ category.categoryName }}
        </a-select-option>
      </a-select>
    </a-form-item>
  </a-form>
</template>

<script lang="ts">
/**
 * modal of Graph file (图数据导入)
 * @author Jinhui Hou
 */
import { Component } from 'vue-property-decorator'
import UploadDataMixin from '@/components/data/basic-information/upload-data-mixin'
import UploadedFileName from '@/components/data/particle-component/UploadedFileName.vue'
import DataUploadStore from '@/store/modules/data-upload'
import DataStore from '@/store/modules/data'
import UserGuideStore from '@/store/modules/user-guide'

@Component({
  components: {
    UploadedFileName,
  },
})
export default class GraphDataForm extends UploadDataMixin {
  public form: any // form table表单
  public fileName: string = '' // 文件名
  public graphFormData: any = null // graphFormData
  private graphFileFormat: string = '' // 图文件格式，json or csv 图数据预览

  public beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'graph_form' })
  }

  /**
   * 神奇
   * @param info
   */
  public handleUpload(info: any) {
    this.handleUploadMixin(info)
  }

  /**
   * 选择文件上传文件
   */
  public async uploadDataset(option: any) {
    // 获取文件名和文件类型
    ;[this.fileName, this.fileType] = option.file.name.toString().split('.')
    const formData = new window.FormData()
    formData.append('filename', option.file.name)
    formData.append('charSet', this.fileCodingType)
    this.graphFormData = formData

    try {
      // excel文件和图文件不需要分块上传
      DataUploadStore.setSpinningMessage('导入中')
      DataUploadStore.setSpinning(true)
      formData.append('file', option.file)
      await this.uploadFile(formData)
    } catch (error) {
      console.error(error)
    }
  }

  /**
   * 上传文件
   */
  public async uploadFile(formData: any) {
    try {
      const response = await DataUploadStore.uploadGraphFile(formData)
      DataUploadStore.setSpinning(false)
      if (response.data.code === 100) {
        const { format, content } = response.data.result
        this.graphFileFormat = format
        DataUploadStore.setGraphFileFormat(format) // 文件格式
        if (format === 'json') {
          const saveData: any =
            content || 'not support preview for other file yet'
          DataUploadStore.setGraphPreviewData(saveData) // 存预览数据
        } else if (format === 'csv' || format === 'gml') {
          DataUploadStore.setGraphPreviewData(content) // 存预览数据
        }
        DataUploadStore.setDataInformationCollapsePanelShow(true)
      } else {
        this.fileList = []
        DataUploadStore.setSpinning(false)
        if (response.data.tip) {
          this.$message.warning(response.data.tip)
        }
      }
    } catch (error) {
      DataUploadStore.setSpinning(false)
      this.fileList = []
      DataUploadStore.setGraphPreviewData(null)
      this.$message.error('数据上传失败，请稍后重试')
      this.loadingText = '导入失败'
      this.uploadingState = 'exception'
      console.error(`upload error: ${error}`)
    }
  }

  /**
   * 删除当前的文件
   */
  public deleteFile() {
    this.fileList = []
    this.fileType = ''
    DataUploadStore.setGraphPreviewData(null)
    DataUploadStore.setDataInformationCollapsePanelShow(false)
  }

  /**
   * DataUploadIndex 父组件调用， 取消上传
   * 必须方法
   */
  public cancelImportData() {
    this.fileName = '' // 文件名称
    this.fileList = []
    this.fileType = '' // 数据类型
    DataUploadStore.initStore()
  }

  /**
   * DataUploadIndex 父组件调用， 确认上传
   * 必须方法
   */
  public handleSubmit() {
    this.form.validateFields(async (error: Error, values: any) => {
      if (!error) {
        // 处理后的 请求参数 加入了 列的是否导入 是否脱敏 等参数
        const passData = this.graphFormData
        passData.append('categoryId', values.categoryId)
        // 解决空文件上传的问题
        // if(!(passData.file && passData.fileList[0] && passData.fileList[0].data && (passData.file[0].data.length > 0))) {
        //   this.$message.error('请确保上传文件包含有效数据')
        //   this.deleteFile()
        //   return
        // }
        DataUploadStore.setSpinningMessage('上传中')
        DataUploadStore.setSpinning(true)
        try {
          const response = await DataUploadStore.writeGraphDataset(passData)
          // 失败
          if (response.data.code !== 100) {
            DataStore.setMessageModalOption({
              visible: true,
              message: '导入数据失败',
              tips: `原因：${response.data.message}\n提示：${response.data.tips}`,
            })
          }
          // 成功
          if (DataUploadStore.writeDatasetSucceed) {
            await DataStore.loadDatasetCategory() // 更新左侧列表
            DataStore.setSelectedDatasetId(-1)
            DataStore.setSelectedGraphFileName(response.data.result)
            DataUploadStore.cancelImport()
            this.$message.success('上传成功！')
            await this.goBackPreView('graph', 0)
            this.$nextTick(() => {
              this.$emit('form-set-selected-keys', [
                `graph-${response.data.result}`,
              ]) // 图文件要带graph-前缀
            })
            // data upload success, user guide to the next step
            UserGuideStore.toSpecifiedGuideStep(5)
          }
          DataUploadStore.setSpinning(false)
        } catch (error_) {
          console.error('writeFinalDataset error:', error_)
          DataUploadStore.setSpinning(false)
        }
      } else {
        console.error('error:', error)
      }
    })
  }

  /**
   * 上传成功后更新图数据列表
   */
  public async updateGraphDataList() {
    await DataStore.listGraphFile()
  }
}
</script>
<style lang="less" scoped>
@import './data-type';
</style>
